<!--
 * @description  : 实地核查
 * @descriptionDetail: 实地核查
 * @copyright    : 浙江烟草
 * @author       : yzp
 * @create       : 2022-09-27 09:58:58
-->
<template>
  <view :class="checkInfo.taskStatus == 3 ? '' : 'page'">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar
      :is-white="false"
      :title="navTitle"
      :custom-back="goBack"
      style="z-index: 99999"
    >
      <view class="nav-right-icon">
        <span @tap="handleShowDetail">
          详情
        </span>
      </view>
    </theme-navbar>
    <!-- #endif -->
    <view class="content">
      <view class="wrap">
        <u-swiper img-mode="scaleToFill" :list="imgList" :effect3d="false" mode="rect"></u-swiper>
      </view>
      <view class="c-title">
        {{ checkInfo.customerName }}
      </view>
      <!-- 检查菜单 -->
      <view style="position: relative;margin-top: 30px;">
        <view class="opt-img">
          <u-row v-if="checkInfo.status !== '02' && !checkInfo.signBeginTime">
            <u-col span="4" style="text-align: right;">
              <u-icon size="108" name="../../../static/check/round-nfc.png" v-if="retailer.nfcNo" @tap="handlerNfc"></u-icon>
              <u-icon size="108" name="../../../static/check/round-nfc2.png" v-else @tap="handlerNfc(1)"></u-icon>
            </u-col>
            <u-col span="4" style="text-align: center;">
              <u-icon size="108" name="../../../static/check/round-scan.png" @tap="handlerScan"></u-icon>
            </u-col>
            <u-col span="4" style="text-align: left;">
              <u-icon size="108" name="../../../static/check/round-checkin.png" @tap="signSheetShow = true"></u-icon>
            </u-col>
          </u-row>
          <u-row v-else>
            <u-col span="12" style="padding-top: 3px;">
              <u-icon name="clock" color="#9e9a00"></u-icon>{{ checkInfo.signBeginTime }} - {{ checkInfo.feedbackTime || '未完成' }}
            </u-col>
          </u-row>
        </view>
        <u-collapse class="task-detail">
          <u-collapse-item title="任务详情" :head-style="{fontWeight: 600, color: '#303133'}" style="padding: 15px 8px;">
            <hc-detail :hcDetail="hcDetail"></hc-detail>
          </u-collapse-item>
        </u-collapse>
        <u-card :title="computeHcTitle" :sub-title="checkResultName" :sub-title-color="checkResultColor" margin="0" border-radius="10" :head-style="headStyle" :body-style="bodyStyle">
          <template #body>
            <!-- 浙江组件 -->
            <dynamic-comp
              v-if="compDataSource.length > 0"
              :bizData="checkInfo" 
              :dataSource="compDataSource"
              :disabled="checkInfo.status == '02' || !checkInfo.signBeginTime"
              @update="handleUpdateHc"
            ></dynamic-comp>
            <u-empty v-else text="暂无配置" mode="order"></u-empty>
          </template>
        </u-card>
      </view>
    </view>
    <view class="bottom-btns" v-if="checkInfo.status !== '02' && checkInfo.signBeginTime">
      <u-row>
        <u-col span="6" style="text-align: center;">
          <u-button @click="handleSendXt" style="border: 2px solid #0079F2;">
            岗员协同
          </u-button>
        </u-col>
        <u-col span="6" style="text-align: center;">
          <u-button type="primary" @click="handleSubmit">
            提交
          </u-button>
        </u-col>
      </u-row>
    </view>
    <!-- 手工签到 -->
    <u-action-sheet :list="signList" v-model="signSheetShow" @click="handlerSign"></u-action-sheet>
    <!-- 核查选中项提示 -->
    <u-popup mode="bottom" height="80%" v-model="auditShow">
      <view>
        <view class="header">
          <u-navbar :is-back="false" :background="{backgroundColor: '#218aff'}" title-color="#FFF" title="核查问题">
            <view class="slot-wrap" slot="right">
              <view style="color:#FFF;padding-right:15px;" @click="handleSubmitSign">
                提交
              </view>
            </view>
          </u-navbar>
        </view>
        <view>
          <u-row v-if="fieldAuditItems&&fieldAuditItems.length>0">
            <u-col span="12" class="desc-list-item" v-for="(s,idx) in fieldAuditItems" :key="idx">
              <span class=" desc-list-item-idx">{{ idx + 1 }}</span> {{ s }}
            </u-col>
          </u-row>
          <u-row v-else>
            <u-col span="12" class="desc-list-item">
              <span class=" desc-list-item-idx">{{ 1 }}</span> {{ '检查无异常' }}
            </u-col>
          </u-row>
        </view>
      </view>
    </u-popup>
  </view>
</template>
<script>
/**
 * 检查详情
 */
import certificateService from "@/service/certificate/certificate.service.js";

import commonService from '@/service/eCigar/common.service'
import {dateUtils,} from "@/common/util"
import fieldAuditService from "@/service/internal/fieldAudit.service.js";
import DynamicComp from './components/dynamic-comp.vue'
import HcDetail from './components/hc-detail.vue'
export default {
  components: { DynamicComp, HcDetail,},
  data() {
    return {
      isOpen: false,
      isSubmit: false,  // 是否提交了检查(用于判断返回时是否刷新列表)
      signSheetShow: false, // 手动签到
      auditShow: false,
      menuOpen: false,
      checkInfo: {},
      retailer: {},
      imgList: [],  // 展示的零售户照片
      headStyle: {
        fontWeight: 600,
        marginTop: '5px',
      },
      bodyStyle: {
        paddingTop: 0,
      },
      longitude: 0, // 经度
      latitude: 0,  // 纬度
      signList: [],
      syncSessionKey: "FIELD_AUDIT_",   // 本地缓存的核查信息key前缀
      hcSessionStorageData: null,   // 缓存的核查列表数据
      compDataSource: [],   // 核查项数据
      fieldAuditItems: [],  // 选中的核查项
      hcDetail: {},   // 核查任务详情
    }
  },
  onLoad(){
    this.checkInfo = this.getRouteParam();
    this.initHcDetail();
    console.log("核查详情", this.checkInfo);
    this.signList = this.$u.dic.getByDictCode(this.$u.dic.DIC_KEYS.I_HANDSIGN_REASON).map(d => Object.assign({}, {text: d.bcbName, value: d.bcbCode,}));
  },
  computed: {
    // 生产缓存key
    genicSessionKey() {
      return () => this.syncSessionKey + this.checkInfo.checkAnnalUuid;
    },
    computeHcTitle() {
      return `核查信息(${this.checkInfo.taskSourceName})${!this.checkInfo.signBeginTime ? '-请先签到' : ''}`;
    },
    checkResultName() {
      return this.checkInfo.checkResult ?  (this.checkInfo.checkResult == '01' ? '正常' : '异常') : '';
    },
    checkResultColor() {
      return this.checkInfo.checkResult ?  (this.checkInfo.checkResult == '01' ? 'green' : 'red') : '';
    },
  },
  mounted () {
    // 查询照片
    this.queryImgs();
    this.getLocation();
    let hcStr = uni.getStorageSync(this.genicSessionKey());
    let hcSessionData = hcStr ? JSON.parse(hcStr) : null;
    // console.log("核查缓存数据", hcSessionData, this.genicSessionKey());
    if (hcSessionData) {
      this.compDataSource = hcSessionData;
      this.hcSessionStorageData = this.$u.deepClone(hcSessionData);
    } else {
      this.getWorkItemsList();
    }
    // 字典数据
    // this.getDicts();
  },
  methods: {
    handleShowDetail() {
      if (!this.checkInfo.licNo) {
        this.$u.error("当前核查对象不是零售户");
        return;
      }
      this.$u.route('pages/retailer/retailerInfo/retailerInfo',{retailerUuid:this.checkInfo.retailerUuid,});
    },
    // 查询展示的零售户照片
    queryImgs() {
      let zmRoot = `${commonService.baseUrl}/commonfile/filestore/downloadFile.do?tk=${uni.getStorageSync("tk")}&fileId=`;
      certificateService.detail(this.checkInfo.retailerUuid).then(dr => {
        // 零售户照片
        if (dr.success) {
          let reta = dr.bean || {};
          reta.storeImageUuid && this.imgList.push({image: zmRoot + reta.storeImageUuid,});
          reta.counterImageUuid && this.imgList.push({image: zmRoot + reta.counterImageUuid,});
          reta.custImageUuid && this.imgList.push({image: zmRoot + reta.custImageUuid,});
          reta.liceImageUuid && this.imgList.push({image: zmRoot + reta.liceImageUuid,});
          reta.backCounterImageUuid && this.imgList.push({image: zmRoot + reta.backCounterImageUuid,});
        }
        // 如果没有照片，显示一个无照片
        if (this.imgList.length == 0) {
          this.imgList.push({image: require("../../../static/check/nophoto.png"),});
        }
      }).catch(err => {
        if (this.imgList.length == 0) {
          this.imgList.push({image: require("../../../static/noImg.png"),});
        }
      });
    },
    // 获取核查项
    getWorkItemsList() {
      this.$modal.showLoading("加载中...");
      // 动态获取核查项组件
      fieldAuditService.listWorkItems(this.checkInfo.checkAnnalUuid).then((res) => {
        this.$modal.hideLoading();
        // console.log("核查项配置", res);
        if(res.success) {
          this.compDataSource = res.data;
          this.hcSessionStorageData = this.$u.deepClone(res.data);
        }else{
          self.$modal.alert(res.msg);
        } 
      }).catch((error) => {
        this.$u.toast(error);
      }); 
    },
    // 定位
    getLocation() {
      if (this.$deviceApi.geolocation) {
        this.$deviceApi.geolocation().then(geo => {
          this.longitude = geo.longitude;
          this.latitude = geo.latitude;
        });
      } else {
        this.longitude = 120.55;
        this.latitude = 32.085;
      }
    },
    // NFC
    handlerNfc(type) {
      if (type || !this.retailer.nfcNo) {
        this.$u.toast("当前零售户未制作NFC");
        return;
      }
      this.$deviceApi.buriedPointFunction && this.$deviceApi.buriedPointFunction('点击实地核查的NFC签到');
      this.$deviceApi.nfcReader().then(code => {
        if (!code) {
          this.$u.toast("无法识别");
          return;
        }
        /*
          现有NFC数据有两种数据格式：
          1：04A0931AAA5280
          2：{content : "1234667890",tagId : "04:48:7c:1a:aa:52:81"}
        */
        let nfcNo = "";
        if (code["tagId"]) {
          nfcNo = code["tagId"].replace(/:/g, "");
        } else {
          nfcNo = code.replace(/:/g, "");
        }
        if (this.retailer.nfcNo.toUpperCase() == nfcNo.toUpperCase()) {
          // 签到
          this.checkSign("02", "");
        } else {
          this.$u.toast(`读取到的NFC信息与当前NFC卡不一致，读取信息【${nfcNo}】，NFC卡信息【${this.retailer.nfcNo}】`);
        }
      }).catch(e => {
        this.$u.toast("无法识别:" + e);
      });
    },
    // 扫码
    handlerScan() {
      this.$deviceApi.scan().then(res => {
        this.$deviceApi.buriedPointFunction && this.$deviceApi.buriedPointFunction('点击实地核查的扫码签到');
        let licNo =  this.getLicenseCode(res);
        if(!this.$u.test.digits(licNo)){
          this.$u.toast('无法识别许可证号');
          return;
        }
        // 识别成功
        if(licNo != this.checkInfo.licNo){
          this.$u.toast("您扫描的信息与当前零售户不一致");
          return;
        }
        this.checkSign("01", "");
      });
    },

    /**
	 * 从扫描或NFC获取的零售户信息中提取许可证号
	 * 不同的地区二维码信息不同，如果无法识别，需要修改本方法，添加相关特列
	 * 通用逻辑：查找到“许可证”后的第一个数字串即认为是许可证号
	 */
    getLicenseCode(scanRetailerInfo){
      scanRetailerInfo = scanRetailerInfo.replace(/[\r\n]/g,"");
      console.log("调试:", scanRetailerInfo);
      let reg = new RegExp(/[0-9]{12}/);
      let lic = '';
      try{
        let exts = reg.exec(scanRetailerInfo);
        lic = exts[0];
      }catch(e){
        console.log(e);
      }
      console.log("调试结果:", lic);
      return lic;
    },
    // 手工签到
    handlerSign(i) {
      this.$deviceApi.buriedPointFunction && this.$deviceApi.buriedPointFunction('点击实地核查的其他签到');
      this.checkSign("03", this.signList[i].value);
    },
    // 签到 reasonCode手工签到编码
    checkSign(signType, reasonCode) {
      let signInfo = this.$u.deepClone(this.checkInfo);
      signInfo.signType = signType;
      signInfo.signBeginTime = dateUtils.dateFormat("yyyy-MM-dd HH:mm:ss", new Date());
      this.$u.loading("正在计算当前位置...");
      signInfo.signType = signType;// 签到方式
      signInfo.signExplain = reasonCode;// 手工签到原因
      signInfo.longitudeIn = this.longitude;
      signInfo.latitudeIn = this.latitude;
      // 计算签到距离
      if(signInfo.longitude && signInfo.latitude){
        let p1 = new AMap.LngLat(signInfo.longitudeIn,signInfo.latitudeIn);
        let p2 = new AMap.LngLat(signInfo.longitude,signInfo.latitude);
        signInfo.deviateDistance = Math.round(p1.distance(p2));
        signInfo.isDeviate = signInfo.deviateDistance > 500 ? 1 : 0;
      }
      this.$u.hideLoading();
      // 如果当前位置与零售位置相差1000米则提示
      if (signInfo.isDeviate) {
        this.$modal.confirm("您当前位置距离零售户" + signInfo.deviateDistance + "米，是否继续签到？", () => {
          // console.log('实地核查',signInfo);
          this.doSignIn(signInfo);
        });
      } else {
        this.doSignIn(signInfo);
      }
    },
    // 提交签到
    doSignIn(signInfo) {
      this.$u.loading("正在签到...");
      fieldAuditService.signIn(signInfo).then(dr => {
        this.$u.hideLoading();
        if (dr.success) {
          this.$u.toast("签到成功");
          /**
           *  00	草稿	草稿
              01	待核查	待核查
              02	已核查	已核查
           */
          this.$set(this.checkInfo, "status", '01');
          this.$set(this.checkInfo, "signBeginTime", signInfo.signBeginTime);
          this.refreshPrevPage();
        } else {
          this.$u.toast("签到失败: " + dr.msg);
        }
      });
    },
    setRightBtns () {
      // 设置右侧标题
      // #ifdef H5-DINGDING
      let menuItemStr = '[{"id": "1", "text": "详情"}';
      this.$deviceApi.setMenu(JSON.parse(menuItemStr), res => {
        this.handleShowDetail();
      });
      // #endif
    },
    // 点击检查提交
    handleSubmit() {
      this.fieldAuditItems = [];
      this.deepGen(this.hcSessionStorageData);
      // 检查提交的数据
      let emptyHcItems = this.hcSessionStorageData.filter(h => this.validHcItemInfo(h));
      if (this.fieldAuditItems && this.fieldAuditItems.length > 0) {
        this.checkField(this.fieldAuditItems).then(d => {
          if(d == false){
            this.$u.toast("请检查所有异常是否全部填写！");
            return;
          }else{
            if (emptyHcItems.length > 0) {
              this.$u.toast("请填写" + emptyHcItems.map(h => `【${h.itemName}】`).join(",") + "异常原因");
              return;
            }else{
              this.auditShow = true;
            }

          }
        })
      }else{
        this.auditShow = true;
      }
      
    },
    checkField(v){
      let p = new Promise(function(resolve, reject){        // 做一些异步操作
        v.forEach(d => {
          if(!d){
            resolve(false);
            return;
          }
          resolve(true);
        })

      });
      return p;
      
    },
    // 发起岗员协同
    handleSendXt() {
      this.$u.route("/pages/internal/docFrame/components/coordinationStart");
    },
    // 刷新上一页的列表
    refreshPrevPage() {
      // 刷新上一页
      let pages = getCurrentPages();
      let prePage = pages[pages.length - 2]; // 上一页
      prePage.$refs['mescrollItem0'].refresh();
    },
    deepGen(arr) {
      if (Array.isArray(arr)) {
        arr.forEach(d => {
          if ((d.defaultValue == '0' ? d.value : !d.value) && typeof d.value === 'boolean') {
            this.fieldAuditItems.push(d.problemDesc);
          } else if (d.operateType === '91404') {
            d.value && this.fieldAuditItems.push(d.itemName + ':' + d.value);
          }
          if (d.children && d.children.length > 0) {
            this.deepGen(d.children);
          }
        });
      }
    },
    // 提交
    handleSubmitSign() {
      this.auditShow = false;
      this.$modal.confirm("确认提交吗？", () => {
        // 获取当前点位信息
        if (this.$deviceApi.geolocation) {
          this.$deviceApi.geolocation().then(geo => {
            this.longitude = geo.longitude;
            this.latitude = geo.latitude;
            doSumit();
          });
        } else {
          doSumit();
        }
      });
      // 提交操作
      let doSumit = () => {
        // console.log("执行提交任务", this.hcSessionStorageData);
        let checkItemList = this.hcSessionStorageData.map(h => {
          if(h.operateType == '91404'){
            h.problemDesc = h.value
          }
          h.checkUuid = this.checkInfo.checkAnnalUuid;
          h.checkData = (h.value == true || h.value == false) ? (typeof h.value == 'boolean' ? (h.value == true ? '1' : '0') : h.value) : h.defaultValue;
          h.isUnusual = h.operateType == '91404' ? '0' : (h.checkData == h.unusualValue ? '1' : '0');
          h.unusualInfo = typeof h.value == 'boolean' ? h.problemDesc : h.value;
          return h;
        });
        // 检查提交的数据
        this.$u.loading("提交中...");
        let fieldCheckAnnal = Object.assign({}, {checkAnnalUuid: this.checkInfo.checkAnnalUuid, 
          longitudeOut: this.longitude, latitudeOut: this.latitude,
      
          checkResultMarket: this.fieldAuditItems.join(","),
        });
        for(let i = 0;i < checkItemList.length;i++){
          if(checkItemList[i].isUnusual == '1' && checkItemList[i].seq != '99'){
            fieldCheckAnnal.checkResult = '02';
            break;
          }else{
            fieldCheckAnnal.checkResult = '01';
          }
        }
        fieldAuditService.saveCheckResults(checkItemList, fieldCheckAnnal).then((res) => {
          this.$u.hideLoading();
          this.$deviceApi.buriedPointFunction && this.$deviceApi.buriedPointFunction('点击实地核查的提交');
          if(res.success){
            this.$u.toast("提交成功");
            // 签退状态
            this.$set(this.checkInfo, "status", "02");
            this.$set(this.checkInfo, "feedbackTime", dateUtils.dateFormat("yyyy-MM-dd HH:mm:ss", new Date()));
            // 提交成功后删除缓存
            uni.removeStorageSync(this.genicSessionKey());
            this.isSubmit = true;
            this.refreshPrevPage();
          } else {
            this.$u.error(res.msg);
          } 
        });
      }
    },
    // 验证核查项输入框内容是否正常，核查项描述!=核查项标签+“:”
    validHcItemInfo(h) {
      if(h.problemDesc && h.itemName){
        return h.itemName + ":" == h.problemDesc.replace(/\s/g, "");
      }
    },
    // 任务详情
    initHcDetail() {
      this.checkInfo.checkAnnalUuid && fieldAuditService.fieldCheckAnnalDetail(this.checkInfo.checkAnnalUuid).then((res) => {
        if(res.success){
       
          if(res.bean == null){
            this.$u.toast("无数据");
          }
          this.hcDetail = res.bean;
        }else{
          this.$u.toast(res.msg);
        } 
      }).catch((error) => {
        this.$u.toast(error);
      });
    },
    // 实时保存录入的核查信息
    handleUpdateHc(hcData) {
      this.genicListFromHcData(hcData);
      console.log("实时保存的数据", this.hcSessionStorageData);
      uni.setStorageSync(this.genicSessionKey(), JSON.stringify(this.hcSessionStorageData));
    },
    // 从选中数据中组装缓存用的核查数据
    genicListFromHcData(hcData) {
      let hcMap = new Map();
      hcData.forEach(h => {
        hcMap.set(h.propName, {
          value: h.value,
          problemDesc: h.children && h.children.length > 0 ? h.children[0].value : "",
        });
      });
      this.hcSessionStorageData.forEach(hc => {
        if (hcMap.has(hc.itemUuid)) {
          hc.value = hcMap.get(hc.itemUuid).value;
          hc.problemDesc = hcMap.get(hc.itemUuid).problemDesc;
        }
      });
    },
  },
}
</script>
<style lang="scss" scoped>
@import "@/style/common/rightMenu.scss";
.content {
  background-color: #FFF;
  padding-bottom:82px;
  .c-title {
    //position: absolute;
    //top: 45px;
    height: 26px;
    line-height: 26px;
    -webkit-border-radius: 13px;
    -moz-border-radius: 13px;
    border-radius: 13px;
    padding: 0 10px;
    background-color: #eaeaea;
    opacity: .8;
    color: #000;
    font-weight: 600;
    font-size: 15px;
    text-align: center;
    width: 100%;
    z-index: 99;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .opt-img {
    position: absolute;
    z-index: 99;
    left: 0px;
    top: -30px;
    width: 100%;
  }
  .grid-text {
    font-size: 28rpx;
		margin-top: 10rpx;
		color: #333;
  }
  .task-detail {
    margin-top: 25px;
    margin-bottom: 5px;
    border-radius: 4px;
    border: 1px solid #f5f6f9;
  }
}
.header {
  height: 45px;
  width: 100%;
  position: sticky;
  top: 0px;
  z-index: 999;
  background-color: #FFF;
}
.desc-list-item {
  padding: 5px !important;
  border-bottom: 1px solid #f0f0f1;
  .desc-list-item-idx {
    border: 1px solid #D0E7FC;
    background: #D0E7FC;
    color: #333;
    border-radius: 50%;
    margin-right: 5px;
    padding: 0px 5px;
    height: 28px;
    line-height: 28px;
    text-align: center;
    font-size: 13px;
  }
}
/deep/ .u-collapse .u-collapse-body {
  overflow-y: auto;
}
</style>